#!/bin/bash
set -o pipefail;

#TODO:activate when ready
# remove these comments and the exit statement; for now fail it
#exit 1

PGNAME=`basename $0`
PGDIRNAME=`dirname $0`
PGERR="$PGNAME[$$]: "
PGUSER=`id -un`


if [ "${MLPROD_HOME}" == "" ]
then
  echo "${PGERR} :  MLPROD_HOME env not set;  exiting !!!" >&2
  exit 10
fi

PGCFG_FILE="${MLPROD_HOME}/config/mlprog.rc"
if [ ! -f ${PGCFG_FILE} ]
then
  echo "${PGERR} : config file <${PGCFG_FILE}> not found; exiting !!!" >&2
  exit 10
fi

. "${PGCFG_FILE}"

CUST_CTX="$(mlget_cust_ctx 'cust')"
MOD_CTX="$(mlget_cust_ctx  'mod')"
BATCH_WFL_ID=1                  # workflow/product id
BATCH_MODE="oper"
if [ ! -z ${BATCH_RUN_MODE} ]
then
  BATCH_MODE="${BATCH_RUN_MODE}"
fi
LOG_CTX="${BATCH_MODE}-${CUST_CTX}"


PGCFG_FILE="${MLPROD_HOME}/cust/${CUST_CTX}/config/${MOD_CTX}.rc"
if [ ! -f ${PGCFG_FILE} ]
then
  echo "${PGERR} : config file <${PGCFG_FILE}> not found; exiting !!!" >&2
  exit 10
fi

. "${PGCFG_FILE}"
if [ ! -f ${PGCFG_FILE} ]
then
  echo "${PGERR} : config file sourcing <${PGCFG_FILE}> error; exiting !!!" >&2
  exit 10
fi


function cleanup
{
  rm -f ${EDER_DSTATUS_FILE};
  rm -f ${EDER_ESTATUS_FILE};

  if [ -f ${OUT_INSURANCE_FILE} ]
  then
    rm -f ${OUT_INSURANCE_FILE}
    if [ $? -ne 0 ]
    then
      mllogerr "[${LOG_CTX}] : ERR : Unable to cleanup files : ${OUT_INSURANCE_FILE}";
    fi
  fi

}

trap cleanup EXIT ERR TERM INT QUIT

function usage()
{
  mllogerr "Usage: $PGNAME -p [0|1|2] -b MMDDYY_HHMMSS_XXXXXX WHERE XXXXXX is cust_id";
}

if [ $# -ne 4 ]
then
  usage;
  exit 10;
fi


PART=-1
DBATE="";
while getopts "p:b:" opts
do
  case $opts in
    p ) PART=$OPTARG
        ;;
    b ) BDATE=$OPTARG
        ;;
    * ) usage; exit 10;
        ;;
  esac
done

if [ ${PART} -lt 0 -o ${PART} -gt 2  -o -z ${BDATE} ]
then
  usage
  exit 10
fi


# get the batch dates BATCH_RECV_DATE, BATCH_RUN_DATE, BATCH_EXEC_DATE
mlget_batch_dates "${BDATE}"
if [ $? -ne 0 ] || [ -z "${BATCH_RECV_DATE}" ]
then
  usage
  exit 10
fi

# LOG
LOG_CTX="${LOG_CTX}-${BATCH_RECV_DATE}"

# ACCOUNT FILE
IN_INSURANCE_FILE=${ARCH_CTX_IN_DIR}/${BATCH_RECV_DATE}_trans.gpg

# RECON OUTPUT FILE
RECON_OUTPUT=${MLARCH_DIR}/recon/in



if [ ! -d ${LOG_CTX_DIR} ]
then
  mkdir -p ${LOG_CTX_DIR}
  if [ $? -ne 0 ]
  then
    mllogerr "[${LOG_CTX}] : ERR : Unable to create log folder : ${LOG_CTX_DIR}";
    exit 10;
  fi
fi

if [ ! -r ${IN_INSURANCE_FILE} ]
then
  mllogerr "[${LOG_CTX}] : ERR : Incoming trans file not found : ${IN_INSURANCE_FILE}";
  exit 10;
fi

tstart=$((`date +%s`))

tstamp="00:00:00"
mllogerr "[${LOG_CTX}] : BEG : [${tstamp}] : BATCH START"


if [ $PART -eq 0 -o $PART -eq 1 ]
then
  ${PGDIRNAME}/run_part_1.sh ${BATCH_RECV_DATE}
  RET=$?
  if [ $RET -ne 0 ]
  then
    mllogerr "[${LOG_CTX}] : ERR : run batch part-1 failed"
    cleanup;
    exit $RET;
  fi
fi

if [ $PART -eq 0 ] && [ $MMACHINE -eq 1 ]
then

        export PGPASSWORD="!#test123#!"

        TT=`echo "select our_run_date       \
                  from                      \
                  trans_output_t            \
                  limit 1;"                 \
           |  psql -A -t -d mlprod_db -h hdb-srv1 -U payorintel_mlprod_u`;


        if [ "${TT}" ]
        then

          MM=${TT:0:2};
          DD=${TT:3:2};
          YY=${TT:8:2};
          HH=${TT:11:2};
          MI=${TT:14:2};
          SS=${TT:17:2};

          CID=${BATCH_RECV_DATE:14:6};
          BATCH_OUTPUT_DATE="${MM}${DD}${YY}_${HH}${MI}${SS}_${CID}";


          TASK_ID=`expr $TASK_ID + 1`
          tmsg="output file into /archive/recon/in folder";
          mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
          ts=$((`date +%s`))
          ${PGSQL} ${SQL_CTX_BAK_DIR}/copy_table_trans_recon.sql > "${RECON_OUTPUT}/${BATCH_OUTPUT_DATE}.recon"
          if [ $? -ne 0 ]
          then
            mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
            cleanup;
            exit -1;
          fi
          te=$((`date +%s`))


          FILE_COUNT=`wc -l "${RECON_OUTPUT}/${BATCH_OUTPUT_DATE}.recon" | grep -i '^0 ' `

          if [ -z "$FILE_COUNT" ]
          then

             TASK_ID=`expr $TASK_ID + 1`
             tmsg="create trigger recon file in /haris/batch/payorintel/recon folder";
             mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
             ts=$((`date +%s`))
             touch "${MLPROD_HOME}/batch/payorintel/recon/${BATCH_OUTPUT_DATE}.0"
             if [ $? -ne 0 ]
             then
               mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
               cleanup;
               exit -1;
             fi
             te=$((`date +%s`))

          else

             rm -f "${RECON_OUTPUT}/${BATCH_OUTPUT_DATE}.recon"

          fi

        fi

fi


tstamp="$(mltstamp ${tstart})"
mllogerr "[${LOG_CTX}] : END : [${tstamp}] : BATCH DONE"

exit 0;
